# @Time : 2022/7/27 13:26
# @Author : zhangzhihui
# @Email : mrzhangzh@gmail.com
import json, datetime, hashlib

import jwt
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer, AsyncJsonWebsocketConsumer, AsyncWebsocketConsumer
from channels.exceptions import StopConsumer

from Administrative_office_system import settings
from correspondence.models import chatting_records, ChatGroups
from personal_center.models import User

consumer_object_list = []
obj_dict = {}
class ChatConsumer(WebsocketConsumer):

    def connect(self):
        """
       客户端发来链接请求之后就会自动触发
       self:连接对象
       message:
       """
        self.accept()  # 进行握手环节 发送加密字符串
        token = self.scope['query_string'].decode('utf-8').split("token=")[1]
        token_dict = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
        self.scope["user"] = User.objects.get(job_number=token_dict['username'])
        obj_dict[self.scope["user"].job_number] = self
        consumer_object_list.append(self)
        # self.room_name = self.scope['path_remaining']
        # self.room_group_name = 'chat_%s' % self.room_name
        # async_to_sync(self.channel_layer.group_add)(
        #     self.room_group_name,
        #     self.channel_name
        # )



    def disconnect(self, close_code):
        """
       客户端主动断开链接之后自动触发
       """
        print('断开链接了')
        # 服务端断开链接 就去列表中删除对应的客户端对象
        consumer_object_list.remove(self)
        del obj_dict[str(self.scope["user"].job_number)]
        raise StopConsumer

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        # for obj in consumer_object_list:
        #     obj.send(text_data)  # 返回给所有的连接对象 实现群聊
        print(text_data_json)
        chat_type = 'private'
        if 'chat_type' in text_data_json:
            chat_type = text_data_json['chat_type']

        if chat_type == 'private':
            text_data_json["date"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
            to_img = str(User.objects.get(job_number=text_data_json["to_user"]).head_portrait)
            text_data_json["to_img"] = "/media/" + to_img if to_img else "/static/personal_center/img/头像.png"
            chatting_records.objects.create(
                from_user=self.scope["user"],
                to_user=User.objects.get(job_number=text_data_json['to_user']),
                content=json.dumps([text_data_json]),
            )
            if text_data_json['to_user'] in obj_dict:
                obj_dict[text_data_json['to_user']].send(text_data)
                print(text_data_json['to_user'])
        else:
            group_obj = ChatGroups.objects.get(room_id=text_data_json['to_user']).group_user.all()
            for obj in group_obj:
                if obj.job_number in obj_dict and obj.job_number != text_data_json['from']:
                    print("===================================", obj.job_number)
                    obj_dict[obj.job_number].send(text_data)


    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        print(event)
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))
